package com.gzw.dms.activity;

import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.gzw.dms.KJ.SelectCityActivity;
import com.gzw.dms.KJ.SelectCustomerActivity;
import com.gzw.dms.MyApplication;
import com.gzw.dms.R;
import com.gzw.dms.base.BaseActivity;
import com.gzw.dms.base.BaseSpinnerAdapter;
import com.gzw.dms.bean.AddressInfo;
import com.gzw.dms.bean.JySuppliersInfo;
import com.gzw.dms.bean.SpinnerInfo;
import com.gzw.dms.bean.UserInfo;
import com.gzw.dms.utils.HttpUtils;
import com.gzw.dms.utils.JsonUtil;
import com.gzw.dms.utils.T;
import com.gzw.dms.utils.UrlUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class SuppliesActivity extends BaseActivity {
    private TextView tv_startTime,tv_endTime;
    private DatePickerDialog start_dpd,end_dpd;
    private Button btn_sign;
    private Context mContext;
    private Toolbar toolbar;
    private TextView ic_adress,tv_fhkh;
    private EditText tv_carnumber, tv_phonetype, tv_phonesate,tv_suppliescompany, tv_supplies,tv_companyuser,tv_person,
            tv_phone,tv_suppliersDeadline,tv_suppliersService;
    private Spinner sp_identity;
    private String  type = "0";
    private JySuppliersInfo info;
    private ProgressDialog mProgressDialog;
    private String adress,driver_province,driver_city,driver_county,fpstste,fhku_id;
    private AddressInfo addressInfo;
    private Intent mIntent;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_supplies);

    }

    @Override
    protected void initViews() {
        ic_adress = (TextView) findViewById(R.id.ic_adress);
        tv_fhkh = (TextView) findViewById(R.id.tv_fhkh);
        tv_startTime=(TextView)findViewById(R.id.tv_start_time);
        tv_endTime=(TextView)findViewById(R.id.tv_end_time);
        btn_sign = (Button) findViewById(R.id.btn_sign);
        toolbar = (Toolbar) findViewById(R.id.toolbar);

        sp_identity = ((Spinner) findViewById(R.id.sp_identity));
        tv_suppliescompany = (EditText) findViewById(R.id.tv_suppliescompany);
        tv_carnumber = (EditText) findViewById(R.id.tv_carnumber);
        tv_phonetype = (EditText) findViewById(R.id.tv_phonetype);
        tv_phonesate = (EditText) findViewById(R.id.tv_phonesate);
        tv_suppliersService = (EditText) findViewById(R.id.tv_suppliersService);
        tv_supplies = (EditText) findViewById(R.id.tv_supplies);
        tv_companyuser = (EditText) findViewById(R.id.tv_companyuser);
        tv_person = (EditText) findViewById(R.id.tv_person);
        tv_phone = (EditText) findViewById(R.id.tv_phone);
        tv_suppliersDeadline = (EditText) findViewById(R.id.tv_suppliersDeadline);
    }

    @Override
    protected void initData() {
        mContext = this;
        mIntent = getIntent();
        fpstste = (String)mIntent.getExtras().get("fpstste");
        if (fpstste.equals("0")){
            toolbar.setTitle("添加供应商");
        }else {
            toolbar.setTitle("修改供应商");

        }
        ArrayList ls = new ArrayList();
        ls.add(new SpinnerInfo("1", "面包车"));
        ls.add(new SpinnerInfo("2", "金杯车"));
        ls.add(new SpinnerInfo("3", "依维柯"));
        ls.add(new SpinnerInfo("4", "4.2箱车"));
        ls.add(new SpinnerInfo("5", "三轮车"));
        ls.add(new SpinnerInfo("6", "3.5箱车"));

        BaseSpinnerAdapter Adapter = new BaseSpinnerAdapter(mContext, ls);
        sp_identity.setAdapter(Adapter);
        addressInfo=new AddressInfo();

        if (fpstste.equals("1")){
            info = (JySuppliersInfo) mIntent.getExtras().get(
                    "driverInfo");
            setData(info);
        }

    }

    @Override
    protected void initEvents() {
        toolbar.setNavigationOnClickListener(new myOnClick());
        tv_startTime.setOnClickListener(new myOnClick());
        tv_endTime.setOnClickListener(new myOnClick());
        tv_fhkh.setOnClickListener(new myOnClick());
        ic_adress.setOnClickListener(new myOnClick());
        btn_sign.setOnClickListener(new myOnClick());

    }

    private void setData(JySuppliersInfo driverInfo) {
        tv_fhkh.setText(driverInfo.getSupplier_customer_name());
        tv_suppliescompany.setText(driverInfo.getSupplie_company());
        tv_supplies.setText(driverInfo.getSuppliersName());
        tv_companyuser.setText(driverInfo.getSuppliersPeople());
        ic_adress.setText(driverInfo.getSuppliersAddress());
        tv_person.setText(driverInfo.getSuppliersPerson());
        tv_phonesate.setText(driverInfo.getPhone_model());
        tv_phonetype.setText(driverInfo.getPhone_brand());
        tv_suppliersService.setText(driverInfo.getSuppliersService());
        tv_phone.setText(driverInfo.getSuppliersPhone());
        tv_carnumber.setText(driverInfo.getSuppliers_carnumber());
        tv_suppliersDeadline.setText(driverInfo.getSuppliersDeadline());
        tv_startTime.setText(driverInfo.getSuppliersStartDate());
        tv_endTime.setText(driverInfo.getSuppliersEndDate());
        btn_sign.setText("修       改");
        driver_province = driverInfo.getDriver_province().toString();
        driver_city = driverInfo.getDriver_city().toString();
        driver_county = driverInfo.getDriver_countyname().toString();
        fhku_id = driverInfo.getSuppliers_customer();
        type=driverInfo.getSuppliers_cartype();
        SpinnerInfo spinnerInfo = (SpinnerInfo) sp_identity.getSelectedItem();
        spinnerInfo.setText(type);
    }
    class myOnClick implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {

                case R.id.tv_start_time:
                    Calendar mCalendar = Calendar.getInstance(Locale.CHINA);
                    int year = mCalendar.get(Calendar.YEAR);
                    int month = mCalendar.get(Calendar.MONTH);
                    int day = mCalendar.get(Calendar.DAY_OF_MONTH);

                    start_dpd = new DatePickerDialog(mContext, new Datelistener(), year, month,
                            day);
                    start_dpd.show();
                    break;
                case R.id.tv_end_time:
                    Calendar mCalendar1 = Calendar.getInstance(Locale.CHINA);
                    int year1 = mCalendar1.get(Calendar.YEAR);
                    int month1 = mCalendar1.get(Calendar.MONTH);
                    int day1 = mCalendar1.get(Calendar.DAY_OF_MONTH);

                    end_dpd = new DatePickerDialog(mContext, new Datelistener1(), year1, month1,
                            day1);
                    end_dpd.show();
                    break;
                case R.id.btn_sign:
                    SaveHttpClientPost();
                    break;
                case R.id.ic_adress:
                    Intent mIntent1 = new Intent();
                    mIntent1.putExtra("who", "0");
                    mIntent1.setClass(mContext, SelectCityActivity.class);
                    startActivityForResult(mIntent1, 2);
                    break;

                case R.id.tv_fhkh:
                    Intent mIntent21 = new Intent();
                    mIntent21.putExtra("type", "0");
                    mIntent21.setClass(mContext, SelectCustomerActivity.class);
                    startActivityForResult(mIntent21, 0);
                    break;
                default:
                    finish();
                    break;
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == 0){
            try {
//                ArrayList<String> name1 = data.getStringArrayListExtra("name");
//                String name2 = name1.toString();
//                String name = name2.substring(1,name2.length()-1);
                String name = data.getStringExtra("name");
                String id = data.getStringExtra("id");

            } catch (Exception e) {
                // TODO: handle exception
            }
        }else if (resultCode == 2){
            try {
                String province = data.getStringExtra("province");
                String city = data.getStringExtra("city");
                String county = data.getStringExtra("county");
                driver_province = data.getStringExtra("province_id");
                driver_city = data.getStringExtra("city_id");
                String county_id = data.getStringExtra("county_id");
                String str2 = county.substring(1, county.length()-1);
                String str = province+city+str2;
                adress=str;
                ic_adress.setText(str);
                driver_county = county_id.substring(1,county_id.length()-1);

            } catch (Exception e) {
                // TODO: handle exception
            }
        }else if (resultCode == 3){
            try {
                String name = data.getStringExtra("name");
                String id = data.getStringExtra("id");
                tv_fhkh.setText(name);
                fhku_id=id;

            } catch (Exception e) {
                // TODO: handle exception
            }

        }


    }
    public void SaveHttpClientPost() {
        if (isNull(tv_fhkh)) {
            T.showShort(mContext, "发货客户不能为空");
            return;
        }

        if (isNull(tv_suppliescompany)) {
            T.showShort(mContext, "供应商公司不能为空");
            return;
        }
        if (isNull(tv_supplies)) {
            T.showShort(mContext, "供应商名称不能为空");
            return;
        }
        if (isNull(ic_adress)) {
            T.showShort(mContext, "地址不能为空");
            return;
        }
        if (isNull(tv_companyuser)) {
            T.showShort(mContext, "公司法人不能为空");
            return;
        }
        if (isNull(tv_person)) {
            T.showShort(mContext, "联系人不能为空");
            return;
        }
        if (isNull(tv_phone)) {
            T.showShort(mContext, "电话不能为空");
            return;
        }
        if (isNull(tv_suppliersDeadline)) {
            T.showShort(mContext, "合同期限不能为空");
            return;
        }
        if (isNull(tv_startTime)) {
            T.showShort(mContext, "开始时间不能为空");
            return;
        }
        if (isNull(tv_endTime)) {
            T.showShort(mContext, "结束时间不能为空");
            return;
        }

        SpinnerInfo spinnerInfo = (SpinnerInfo) sp_identity.getSelectedItem();
        type = spinnerInfo.getText();

        if (info == null)
            info = new JySuppliersInfo();
        info.setSupplie_company(tv_suppliescompany.getText().toString().trim());
        info.setSuppliersName(tv_supplies.getText().toString().trim());
        info.setSuppliersPeople(tv_companyuser.getText().toString().trim());
        info.setSuppliersAddress(ic_adress.getText().toString().trim());
        info.setSuppliersPerson(tv_person.getText().toString().trim());
        info.setSuppliersPhone(tv_phone.getText().toString().trim());
        info.setPhone_model(tv_phonesate.getText().toString().trim());
        info.setPhone_brand(tv_phonetype.getText().toString().trim());
        info.setSuppliers_carnumber(tv_carnumber.getText().toString().trim());
        info.setSuppliers_cartype(type);
        info.setDriver_countyname(driver_county);
        info.setDriver_city(Integer.parseInt(driver_city));
        info.setDriver_province(Integer.parseInt(driver_province));
        info.setSuppliersService(tv_phonetype.getText().toString().trim());
        info.setSuppliersDeadline(tv_suppliersDeadline.getText().toString().trim());
        info.setSuppliersStartDate(tv_startTime.getText().toString().trim());
        info.setSuppliersEndDate(tv_endTime.getText().toString().trim());
        info.setSuppliers_customer(fhku_id);
        if (fpstste.equals("1")){
            Change change = new Change();
            change.execute(info);
        }else {
            SignShipOrder signShipOrder = new SignShipOrder();
            signShipOrder.execute(info);
        }
    }

    public class SignShipOrder extends AsyncTask<JySuppliersInfo, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {
            mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
            mProgressDialog.setCancelable(true);
            mProgressDialog.setCanceledOnTouchOutside(false);

        }

        protected String doInBackground(JySuppliersInfo... params) {
            Map<String, Object> map = new HashMap<>();
            UserInfo userInfo = MyApplication.getUserInfo();
            map.put("userName", userInfo.getUsername());
            map.put("suppliers", params[0]);
            String json = JsonUtil.toJson(map);
            return HttpUtils.doPost(UrlUtils.getInstance().getJavaUrl("appAddSupplersInfo"), "json=" + json);
        }

        @Override
        protected void onPostExecute(final String result) {
            mProgressDialog.dismiss();
            if (isNull(result)) {
                T.showShort(mContext, "连接服务器异常");
            } else {

                if (result.indexOf("errorMsg") > 0) {
                    String errorMsg = JsonUtil.getMsg(result, "errorMsg");
                    T.showShort(mContext, errorMsg);
                } else {
                    String successMsg = JsonUtil.getMsg(result, "successMsg");
                    T.showShort(mContext, successMsg);
                    Intent mIntent = new Intent();
                    //把返回数据存入Intent
                    mIntent.putExtra("result", 1);
                    //设置返回数据
                    setResult(1, mIntent);
                    finish();
                }
            }
        }

        @Override
        protected void onCancelled() {

        }
    }


    public class Change extends AsyncTask<JySuppliersInfo, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {
            mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
            mProgressDialog.setCancelable(true);
        }

        protected String doInBackground(JySuppliersInfo... params) {
            Map<String, Object> map = new HashMap<>();
            UserInfo userInfo = MyApplication.getUserInfo();
            map.put("userName", userInfo.getUsername());
            map.put("suppliers", params[0]);
            String json = JsonUtil.toJson(map);
            return HttpUtils.doPost(UrlUtils.getInstance().getJavaUrl("appUpdateSupplersInfo"), "json=" + json);
        }

        @Override
        protected void onPostExecute(final String result) {
            mProgressDialog.dismiss();
            if (isNull(result)) {
                T.showShort(mContext, "连接服务器异常");
            } else {

                if (result.indexOf("errorMsg") > 0) {
                    String errorMsg = JsonUtil.getMsg(result, "errorMsg");
                    T.showShort(mContext, errorMsg);
                } else {
                    String successMsg = JsonUtil.getMsg(result, "successMsg");
                    T.showShort(mContext, successMsg);
                    Intent mIntent = new Intent();
                    //把返回数据存入Intent
                    mIntent.putExtra("result", 1);
                    //设置返回数据
                    setResult(1, mIntent);
                    finish();
                }
            }
        }

        @Override
        protected void onCancelled() {

        }
    }

    class Datelistener implements DatePickerDialog.OnDateSetListener {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            // TODO Auto-generated method stub
            tv_startTime.setText(year + "-" + (monthOfYear + 1) + "-"
                    + dayOfMonth);
        }
    }

    class Datelistener1 implements DatePickerDialog.OnDateSetListener {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            // TODO Auto-generated method stub
            tv_endTime.setText(year + "-" + (monthOfYear + 1) + "-"
                    + dayOfMonth);
        }
    }


}
